using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.ServiceModel;
using System.Windows;
using EndToEndSilverlightDemo.NorthWindServiceReference;

namespace EndToEndSilverlightDemo
{
    public class ProductSearchController : IProductSearchController
    {
        private readonly IProductSearchService productSearchService;
        private readonly IProductSearchView productSearchView;
        private readonly IApplication application;
        private readonly IApplicationSettings settings;


        public ProductSearchController(IProductSearchView view, IApplication application, IProductSearchService productSearchService, IApplicationSettings settings)
        {
            this.productSearchService = productSearchService;
            this.productSearchView = view;
            this.application = application;
            this.settings = settings;

            view.SearchButtonClicked += new EventHandler<EventArgs<string>>(this.OnSearchButtonClicked);
            productSearchService.GetProductsCompleted += GetProductsCompleted;

        }

        public virtual void GetProductsCompleted(object sender, EventArgs<IEnumerable<Product>> e)
        {
            productSearchView.SetGridProductItems(e.Value);
            settings.LastProductSearchResults = (Product[]) e.Value;
            settings.Save();
        }

        private void OnSearchButtonClicked(object sender, EventArgs<string> productSearchString)
        {
            productSearchService.GetProductsAsync(productSearchString.Value);
        }


        public virtual void Run()
        {
            application.RootVisual = (DependencyObject) productSearchView;
            if(settings.LastProductSearchResults!=null)
                productSearchView.SetGridProductItems(settings.LastProductSearchResults);
        }
    }
}